<!-- eslint-disable no-unused-vars -->
<template>
  <div>
    <div class="n-layout-page-header">
      <n-card :bordered="false" class="mt-4 proCard">
        <n-input-group>
          <n-input
            placeholder="请输入账号"
            :style="{ width: '300px' }"
            v-model:value="params.username"
          />
          <n-button type="info" @click="reloadTable()">
            <n-icon size="18"> <Search /> </n-icon> 搜索
          </n-button>
        </n-input-group>
      </n-card>
    </div>
    <n-card :bordered="false" class="mt-4 proCard">
      <BasicTable
        :columns="columns"
        :request="loadDataTable"
        :row-key="(row) => row.id"
        ref="actionRef"
        :actionColumn="actionColumn"
        @update:checked-row-keys="onCheckedRow"
      >
        <template #tableTitle>
          <n-button type="primary" @click="handleAdd">
            <template #icon>
              <n-icon>
                <PlusOutlined />
              </n-icon>
            </template>
            添加用户
          </n-button>
        </template>

        <template #action>
          <TableAction />
        </template>
      </BasicTable>
    </n-card>
    <n-drawer v-model:show="showModal" :width="502">
      <n-drawer-content>
        <template #header> {{ addUserFlag ? '新增用户' : '编辑用户' }} </template>
        <template #footer>
          <n-button :loading="formBtnLoading" @click="confirmForm">提交</n-button>&nbsp;
          <n-button @click="resetForm">重置</n-button>
        </template>
        <n-spin :show="loadModal">
          <n-form
            ref="formRef"
            label-placement="left"
            label-width="auto"
            :model="userFormState"
            :rules="userFormRules"
          >
            <n-form-item label="账号" path="username">
              <n-input
                v-model:value="userFormState.username"
                placeholder="输入账号"
                :disabled="!addUserFlag"
              />
            </n-form-item>
            <n-form-item label="用户名" path="nickname">
              <n-input v-model:value="userFormState.nickname" placeholder="输入用户名" />
            </n-form-item>
            <n-form-item label="密码" path="password">
              <n-input
                type="password"
                show-password-on="mousedown"
                placeholder="密码"
                v-model:value="userFormState.password"
                :maxlength="125"
              />
            </n-form-item>
            <n-form-item label="确认密码" path="reenteredPassword">
              <n-input
                type="password"
                show-password-on="mousedown"
                placeholder="确认密码"
                v-model:value="userFormState.reenteredPassword"
                :maxlength="125"
              />
            </n-form-item>
            <n-form-item label="邮箱" path="email">
              <n-input v-model:value="userFormState.email" placeholder="输入邮箱" />
            </n-form-item>
            <n-form-item label="角色" path="roleIds">
              <n-select v-model:value="userFormState.roleIds" multiple :options="roles" clearable />
            </n-form-item>
          </n-form>
        </n-spin>
      </n-drawer-content>
    </n-drawer>
  </div>
</template>

<script lang="ts" setup>
  import { reactive, ref, unref, h } from 'vue';
  import { useMessage } from 'naive-ui';
  import { BasicTable, TableAction } from '@/components/Table';
  import { getUserList } from '@/api/system/user';
  import { columns } from './columns';
  import { PlusOutlined } from '@vicons/antd';
  import { Search } from '@vicons/ionicons5';
  import { getUserInfoById, addUserInfo, updateUserInfo, deleteUserInfo } from '@/api/system/user';
  import { getAllRoles } from '@/api/system/role';

  const message = useMessage();
  const actionRef = ref();
  const formRef: any = ref(null);

  const showModal = ref(false);
  const loadModal = ref(false);
  const formBtnLoading = ref(false);
  const addUserFlag = ref(false);

  const params = reactive({
    pageSize: 10,
    username: '',
  });

  const actionColumn = reactive({
    width: 250,
    title: '操作',
    key: 'action',
    fixed: 'right',
    render(record) {
      return h(TableAction, {
        style: 'button',
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
            ifShow: () => {
              return true;
            },
            auth: ['system_user_upd'],
          },
          {
            label: '删除',
            popConfirm: {
              title: '您确定要删除吗？',
              confirm: handleDelete.bind(null, record),
            },
            ifShow: () => {
              return true;
            },
            auth: ['system_user_del'],
          },
        ],
      });
    },
  });

  const roles = ref([]);

  const userFormState = reactive({
    userId: undefined,
    username: '',
    nickname: '',
    password: '',
    reenteredPassword: '',
    email: '',
    description: '',
    status: '',
    roleIds: [],
  });

  const validatePasswordStartWith = (rule, value) => {
    return (
      userFormState.password &&
      userFormState.password.startsWith(value) &&
      userFormState.password.length >= value.length
    );
  };
  const validatePasswordSame = (rule, value) => value === userFormState.password;

  const userFormRules = {
    username: { required: true, message: '请输入账号', trigger: 'blur' },
    nickname: { required: true, message: '请输入用户名称', trigger: 'blur' },
    email: { required: true, message: '请输入用户名', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' },
    reenteredPassword: [
      {
        required: true,
        message: '请再次输入密码',
        trigger: ['input', 'blur'],
      },
      {
        validator: validatePasswordStartWith,
        message: '两次密码输入不一致',
        trigger: 'input',
      },
      {
        validator: validatePasswordSame,
        message: '两次密码输入不一致',
        trigger: ['blur', 'password-input'],
      },
    ],
    roleIds: {
      type: 'array',
      required: true,
      message: '请选择角色',
      trigger: ['blur', 'change'],
    },
  };

  const loadDataTable = async (res: any) => {
    let _params = {
      ...unref(params),
      ...res,
    };
    return await getUserList(_params);
  };

  function onCheckedRow(rowKeys: any[]) {
    console.log(rowKeys);
  }

  function resetForm() {
    formRef.value?.restoreValidation();
    userFormState.userId = undefined;
    userFormState.username = '';
    userFormState.nickname = '';
    userFormState.password = '';
    userFormState.reenteredPassword = '';
    userFormState.email = '';
    userFormState.description = '';
    userFormState.status = '';
    userFormState.roleIds = [];
  }

  function reloadTable() {
    actionRef.value.reload();
  }

  function confirmForm(e: any) {
    e.preventDefault();
    formBtnLoading.value = true;
    formRef.value.validate(async (errors) => {
      if (!errors) {
        console.log(userFormState);
        if (
          (userFormState.password || userFormState.reenteredPassword) &&
          userFormState.password != userFormState.reenteredPassword
        ) {
          message.error('两次密码不一致');
          return;
        }
        if (addUserFlag.value) {
          await addUserInfo(userFormState);
        } else {
          await updateUserInfo(userFormState);
        }
        message.success('保存成功');
        showModal.value = false;
        reloadTable();
      } else {
        message.error('请填写完整信息');
      }
      formBtnLoading.value = false;
    });
  }

  async function handleAdd() {
    console.log('点击了新增');
    showModal.value = true;
    addUserFlag.value = true;
    // 表单校验规则更新
    passwordRuleUpd();
    const dataRoles = await getAllRoles();
    roles.value = dataRoles.map((r) => new Object({ label: r.name, value: r.id }));
    // 重置表单
    resetForm();
  }

  async function handleEdit(record: Recordable) {
    console.log('点击了编辑', record);
    showModal.value = true;
    loadModal.value = true;
    addUserFlag.value = false;
    // 表单校验规则更新
    passwordRuleUpd();
    const dataRoles = await getAllRoles();
    roles.value = dataRoles.map((r) => new Object({ label: r.name, value: r.id }));
    const { data } = await getUserInfoById(record.userId);
    loadModal.value = false;
    userFormState.userId = data.userId;
    userFormState.username = data.username;
    userFormState.nickname = data.nickname;
    userFormState.email = data.email;
    userFormState.description = data.description;
    userFormState.status = data.status;
    userFormState.roleIds = data.roleIds;
  }

  async function handleDelete(record: Recordable) {
    console.log('点击了删除', record);
    await deleteUserInfo(record.userId);
    message.success('删除成功');
    reloadTable();
  }

  function passwordRuleUpd() {
    if (addUserFlag.value) {
      userFormRules.password.required = true;
      userFormRules.reenteredPassword[0].required = true;
    } else {
      userFormRules.password.required = false;
      userFormRules.reenteredPassword[0].required = false;
    }
  }
</script>

<style lang="less" scoped></style>
